/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2023-2023. All rights reserved.
 * Description: stats file service class
 */

#include "ai_stats_file_service.h"

#include <sys/mman.h>

#include "infra/base/assertion.h"
#include "infra/om/stats/ai_stats_log_common.h"
#include "infra/om/stats/ai_stats_log_utils.h"
#include "infra/rpc/serialize.h"
#include "infra/rpc/rpc_handler_registrar.h"

#include "ai_stats_log_file_writer.h"

using namespace hiai::rpc;

namespace hiai {
hiai::Status AIStatsFileService::Execute(int32_t pid, int32_t commandID,
    const std::vector<hiai::rpc::RpcHandle>& inputs, std::vector<hiai::rpc::RpcHandle>& outputs)
{
    (void)pid;
    (void)commandID;
    (void)outputs;

    HIAI_EXPECT_TRUE(inputs.size() == 1);
    void* memAddr = mmap(nullptr, static_cast<size_t>(static_cast<uint32_t>(inputs[0].size)),
        PROT_READ | PROT_WRITE, MAP_SHARED, inputs[0].fd, 0);
    HIAI_EXPECT_TRUE(memAddr != MAP_FAILED);

    std::string codestr(reinterpret_cast<char*>(memAddr), inputs[0].size);
    InStream is(codestr);
    AiStatsEngineType type = hiai::AiStatsEngineType::AI_STATS_START;
    std::string message;
    is >> type >> message;
    munmap(memAddr, static_cast<size_t>(static_cast<uint32_t>(inputs[0].size)));
    HIAI_EXPECT_TRUE(is.IsValid());

    std::map<AiStatsEngineType, std::atomic<bool>>::const_iterator iter =
        AiStatsLogCfgUtils::isMMLogSwitchOpen_.find(type);
    if (iter != AiStatsLogCfgUtils::isMMLogSwitchOpen_.end() && iter->second) {
        AiStatsLogFileWriter* statsLogWriter = AiStatsLogFileWriter::GetInstance();
        statsLogWriter->WriteMessage(type, message);
    }

    return SUCCESS;
}

void AIStatsFileService::OnClientDie(pid_t pid)
{
    (void)pid;
    return;
}

int32_t AIStatsFileService::GetModuleID() const
{
    return AI_STATS_MODULEID;
}

hiai::Status AIStatsFileService::SetListener(
    int pid, const std::vector<hiai::rpc::RpcHandle>& paras, const std::shared_ptr<hiai::rpc::IRPCListener> rpcListener)
{
    (void)pid;
    (void)paras;
    (void)rpcListener;
    return SUCCESS;
}

hiai::Status AIStatsFileService::DestroyFd(std::vector<hiai::rpc::RpcHandle>& outputs)
{
    (void)outputs;
    return SUCCESS;
}

hiai::rpc::RULE STATS_ACCEPT_ALL = MAKE_RULE(REGION, {0, INT_MAX});
ITF_CTL STATS_DEFAULT = {STATS_ACCEPT_ALL};

static const MODULE_RULE statsRule = {
    STATS_DEFAULT,
    {
        {
            {
                CMD_AI_STATS_WRITE_FILE
            },
            STATS_DEFAULT
        }
    },
    STATS_DEFAULT,
    STATS_DEFAULT
};

REGISTER_RPC_HANDLER_CREATOR(StatsFileService, AIStatsFileService, statsRule);
} // namespace hiai
